<template>
  <div class="detail-record full-height page-content bg-white content padding-20 scrollbar">
    <q-form class="dialog-content form-inline block no-padding overflow-hidden full-height">
      <div style="height:calc(100% - 42px); overflow-y: auto; overflow-x:hidden" class="scrollbar">
      <device-detail title="设备信息" ref="deviceDetail" />
      <div class="q-mb-md">
        <q-separator class="qa-line"/>
      </div>
      <maintenance-information title="保养信息" ref="maintenanceInformation" @onComplete_M="onComplete_M" :supplementaryRecordStatus="supplementaryRecordStatus"/>
        <div class="q-mt-md q-mb-md">
            <q-separator class="qa-line"/>
        </div>
        <spare-table style="margin: 0px -20px" :spareData="maintenaceOrderData.bindingApply" v-if="maintenaceOrderData.bindingApply" ref="SpareTable" :isShowCount="maintenaceOrderData.status !== Enums.MAINTENANCE_STATUS.REPAIRING.value"></spare-table>
        <process-progress title="处理进度" ref="processProgress" />
      </div>
      <div class="dialog-footer text-center margin-t-10">
            <q-btn outline label="返回" color="primary" @click="onBcak" class="qa-btn q-mr-md"/>
            <q-btn outline label="强制关闭" color="primary" @click="onForcedClose" v-if="isShowTransferBtn" class="qa-btn q-mr-md"/>
            <q-btn label="执行" color="primary" @click="onImplement" v-if="isShowImplementBtn" class="qa-btn q-mr-md"/>
            <q-btn label="结束" color="primary" @click="onFinish" v-if="isShowFinishBtn" class="qa-btn q-mr-md"/>
            <q-btn outline label="工单转移" color="primary" @click="onTransferOrder" v-if="isShowTransferBtn" class="qa-btn q-mr-md"/>
            <q-btn outline label="补录" v-has="{id: Enums.SYS_PERMISSION.SUPPLEMENTARY_RECORD_BTN.value}"
                   color="primary" v-if="isSupplementaryRecordBtn" @click="supplementaryRecordStatus=true" class="qa-btn q-mr-md"/>
      </div>
    </q-form>
    <q-inner-loading :showing="isScreenLoading" style="z-index: 99">
      <q-spinner-gears size="50px" color="primary" />
    </q-inner-loading>
    <force-close-dialog :show="isShowForceCloseDialog" @close="isShowForceCloseDialog = false" @setForceClose="setForceClose" />
    <people-select ref="people" @selectUser="selectUser"/>
  </div>
</template>
<script>
import deviceDetail from './common/device-detail'
import processProgress from './common/process-progress'
import PeopleSelect from '../maintenance-plan/common/people'
import maintenanceInformation from './common/maintenance-information'
import forceCloseDialog from './common/force-close-dialog'
import {
  getMaintenaceOrderById,
  postStartMaintenance,
  postCloseMaintenance,
  postChangeMaintenance, supplementMaintenance, postCompleteMaintenance
} from 'src/boot/maintenance/maintenance-order'
import { mapGetters, mapMutations } from 'vuex'
import _ from 'lodash'
import moment from 'moment'
import SpareTable from '../../spare/spare-table'
const backList = [1, 3, 4]
const transferList = [1, 2]
export default {
  name: 'detail-order',
  components: {
    SpareTable,
    processProgress,
    deviceDetail,
    maintenanceInformation,
    forceCloseDialog,
    PeopleSelect
  },
  data () {
    return {
      maintenaceOrderData: {
        maintenanceStatus: null
      },
      orderId: '', // 单子的id
      isScreenLoading: false,
      isShowForceCloseDialog: false,
      supplementaryRecordStatus: false
      // 保养状态
    }
  },
  computed: {
    // 待保养 , 已保养, 过期.
    isOnlyBack () {
      return backList.includes(this.maintenaceOrderData.maintenanceStatus)
    },
    // 执行
    isShowImplementBtn () {
      return this.maintenaceOrderData.maintenanceStatus === 1
    },
    // 结束
    isShowFinishBtn () {
      return this.maintenaceOrderData.maintenanceStatus === 2 || this.supplementaryRecordStatus
    },
    // 工单待保养与保养中可进行工单转移
    isShowTransferBtn () {
      return transferList.includes(this.maintenaceOrderData.maintenanceStatus)
    },
    // 补录按钮
    isSupplementaryRecordBtn () {
      return this.maintenaceOrderData.maintenanceStatus === 4 && !this.supplementaryRecordStatus
    },
    ...mapGetters(['footprint'])
  },
  beforeRouteEnter (to, from, next) {
    to.name === 'detailOrder' && next(vm => {
      vm.getMaintenaceOrderById()
    })
  },
  mounted () {},
  methods: {
    onBcak () {
      const footprint = this.footprint.filter(v => !v.link.includes('detail-order'))
      this.set_footprint(footprint)
      this.$router.push({ path: `/main/repair/maintenance-order` })
    },
    setForceClose (val) {
      this.isShowForceCloseDialog = false
      this.onClose_M(val)
    },
    // 人员选择
    selectUser (userInfo) {
      const newOperatorIds = _.map(userInfo, 'id')
      const params = {
        orderId: this.orderId,
        newOperatorIds
      }
      this.onTransfer_M(params)
    },
    // 转移
    onTransferOrder () {
      this.$refs.people.showDialog()
    },
    onImplement () {
      this.$utils.showMessage('icontubiao-28', '确认要开始执行此保养工单吗?', () => {
        this.onStart_M()
      }, true)
    },
    onFinish () {
      this.$utils.showMessage('icontubiao-28', '确认要结束此保养工单吗?', () => {
        this.$refs.maintenanceInformation.setM_Img()
      }, true)
    },
    onForcedClose () {
      this.isShowForceCloseDialog = true
    },
    // 时间比较 当天的时间和计划保养日期比较,没到日期不让执行
    onDiff_Date () {
    },
    // 开始保养
    async onStart_M () {
      const params = this.$refs.maintenanceInformation.setM_Data()
      params['orderId'] = this.orderId
      const startDay = moment(new Date(new Date().setHours(0, 0, 0, 0)))
      const endDay = moment(this.maintenaceOrderData.scheduledStartDate)
      let diff = endDay.diff(startDay, 'days')
      if (diff > 0) {
        this.$message.warning('未到保养计划开始时间，无法开始保养！')
        return
      }
      try {
        this.isScreenLoading = true
        const ret = await postStartMaintenance(params)
        ret.success && this.getMaintenaceOrderById()
      } catch (error) {
        this.isScreenLoading = false
        this.getMaintenaceOrderById()
        console.log(error)
      }
    },
    // 结束保养
    async onComplete_M (val) {
      const member = { ...val }
      if (this.maintenaceOrderData.bindingApply) {
        member.spareParts = this.$refs.SpareTable.tableData.map(v => {
          return {
            count: v.useCount,
            id: v.sparePartId
          }
        })
        const itemData = this.$refs.SpareTable.tableData
        if (itemData.some(v => v.useCount === '')) {
          this.$message.warning('消耗数量不能为空')
        }
      }
      member['orderId'] = this.orderId
      if (member.maintenanceOrderItemLogList.some(v => v.status === '')) {
        this.$message.warning('存在未确认的项目内容！')
        return
      }
      if (this.supplementaryRecordStatus) {
        try {
          this.isScreenLoading = true
          const ret = await supplementMaintenance(member)
          this.supplementaryRecordStatus = false
          ret.success && this.getMaintenaceOrderById()
        } catch (error) {
          this.isScreenLoading = false
          this.getMaintenaceOrderById()
          console.log(error)
        }
      } else {
        try {
          this.isScreenLoading = true
          const ret = await postCompleteMaintenance(member)
          ret.success && this.getMaintenaceOrderById()
        } catch (error) {
          this.isScreenLoading = false
          this.getMaintenaceOrderById()
          console.log(error)
        }
      }
    },
    // 强行关闭
    async onClose_M (remark) {
      const params = this.$refs.maintenanceInformation.setM_Data()
      params['orderId'] = this.orderId
      params['remark'] = remark
      try {
        this.isScreenLoading = true
        const ret = await postCloseMaintenance(params)
        ret.success && this.getMaintenaceOrderById()
      } catch (error) {
        this.isScreenLoading = false
        this.getMaintenaceOrderById()
        console.log(error)
      }
    },
    // 工单转移
    async onTransfer_M (params) {
      const that = this
      try {
        this.isScreenLoading = true
        const ret = await postChangeMaintenance(params)
        ret.success && this.$message.success('工单转移成功')
        this.$nextTick(() => {
          that.onBcak()
        })
      } catch (error) {
        this.isScreenLoading = false
        this.onBcak()
        console.log(error)
      }
    },
    // 置空数据
    refresh () {
      this.$refs.deviceDetail.detailData = {}
      this.$refs.processProgress.tableData = []
      this.$refs.maintenanceInformation.refresh()
    },
    // 获取详情列表
    getMaintenaceOrderById () {
      this.isScreenLoading = true
      const id = this.$route.query.id
      this.orderId = this.$route.query.id
      this.refresh()
      this.maintenanceStatus = Number(this.$route.query.maintenanceStatus)
      getMaintenaceOrderById(id).then((result) => {
        this.maintenaceOrderData = _.cloneDeep(result.data)
        // 设备信息
        this.$refs.deviceDetail.detailData = this.maintenaceOrderData.deviceInfor
        // 处理进度
        this.$refs.processProgress.tableData = this.maintenaceOrderData.progresses
        // 保养信息
        this.$refs.maintenanceInformation.initData(this.maintenaceOrderData)
        this.isScreenLoading = false
      }).catch((err) => {
        this.isScreenLoading = false
        console.log(err)
      })
    },
    ...mapMutations({
      'set_footprint': 'SET_FOOTPRINT'
    })
  }
}
</script>
